﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace RollbackLib.src.utils
{
    public class XMLUtils
    {
        /// <summary>
        /// Serialize any object to an XML file using a 3 step approach which guarantees the integrity of the saved file.
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="o"></param>
        public static void SaveObjectToXML(string filePath, Object o)
        {
            //log.Debug("Saving XML file " + filePath + " of type " + o.GetType());
            XmlSerializer SerializerObj = new XmlSerializer(o.GetType());
            // Step 1. Save the file to a temporary name.
            string filePathSave = filePath + ".save";
            using (TextWriter WriteFileStream = new StreamWriter(filePathSave))
            {
                SerializerObj.Serialize(WriteFileStream, o);
                WriteFileStream.Close();
            }

            // Step 2. Rename the existing file to a temporary name.
            string filePathOld = filePath + ".old";
            if (File.Exists(filePath))
            {
                File.Delete(filePathOld);
                File.Move(filePath,filePathOld);
            }

            // Step 3. Rename the file in step 1 to the target filename
            File.Move(filePathSave,filePath);
            if (File.Exists(filePathOld))
            {
                File.Delete(filePathOld);
            }
        }

        /// <summary>
        /// Deserialize an object from a XML file.
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public static Object DeSerializeFromXML(string filePath, Type t)
        {
            //log.Debug("Reading XML file <" + filePath + "> of type <" + t + ">");
            XmlSerializer SerializerObj = new XmlSerializer(t);
            Object o = null;
            using (TextReader reader = new StreamReader(filePath))
            {
                o = SerializerObj.Deserialize(reader);
                reader.Close();
            }
            return o;
        }
    }
}
